﻿using System.Collections.Generic;
using System.Linq;
using QFramework;

namespace ProjectMyFarmAndShe
{
    public interface IShopSystem : ISystem
    {
        List<ShopData> ShopItems { get; }
        List<ShopData> CanBuyShopItem { get; }
        List<ShopData> GetRandShopItems();
        void ResetShopItemData();
    }
    
    public class ShopSystem : AbstractSystem,IShopSystem
    {
        public List<ShopData> ShopItems { get; private set; }
        public List<ShopData> CanBuyShopItem { get; private set; } = new List<ShopData>();

        public ShopData AddShopItem(ShopData shopData)
        {
            ShopItems.Add(shopData);
            return shopData;
        }

        protected override void OnInit()
        {
            ShopItems = new List<ShopData>();

            var saveUtility = this.GetUtility<ISaveUtility>();
            
            AddShopBuyItems.AddShopItem(this);
            AddShopSellItems.AddShopItem(this);

            GetRandShopItems();
            
            foreach (var shopData in ShopItems.Where(data=>data.Type == ShopItemType.Buy))
            {
                shopData.Count.Value = saveUtility.LoadInt(shopData.Key, 20);
            }
            
            saveUtility.AddSaveDataAction(utility =>
            {
                foreach (var shopData in ShopItems.Where(data=>data.Type == ShopItemType.Buy))
                {
                    utility.SaveInt(shopData.Key,shopData.Count.Value);
                }
            });
        }
        
        public List<ShopData> GetRandShopItems()
        {
            CanBuyShopItem.Clear();

            var list = ShopItems.Where(data => data.Type == ShopItemType.Buy).ToList();
            
            for (var i = 0; i < 4; i++)
            {
                var item = list.GetRandomItem();
                list.Remove(item);
                CanBuyShopItem.Add(item);
            }

            return CanBuyShopItem;
        }

        public void ResetShopItemData()
        {
            foreach (var shopData in ShopItems.Where(data=>data.Type == ShopItemType.Buy))
            {
                shopData.Count.Value = 20;
            }
        }
    }
}